package com.myzl.stream.util;

import com.myzl.common.constant.CacheConstants;
import com.myzl.common.core.redis.RedisCache;
import com.myzl.common.utils.StringUtils;
import com.myzl.common.utils.spring.SpringUtils;
import com.myzl.stream.pojo.CameraCache;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

/**
 * @author Administrator
 */
@Slf4j
public class MediaVideoUtils {

    public static void initConnect(Integer key){
        synchronized (MediaVideoUtils.class){
            CameraCache cache = SpringUtils.getBean(RedisCache.class).getCacheObject(getCacheKey(key));
            if (StringUtils.isNotNull(cache)){
                cache.setCount(cache.getCount()+1);
            } else {
                cache = new CameraCache();
                cache.setKey(key);
                cache.setCount(1);
            }
            SpringUtils.getBean(RedisCache.class).setCacheObject(getCacheKey(key),cache,15,TimeUnit.MINUTES);
        }
    }

    public static void destroyConnect(Integer key){
        synchronized (MediaVideoUtils.class){
            CameraCache cache =  SpringUtils.getBean(RedisCache.class).getCacheObject(getCacheKey(key));
            if (StringUtils.isNotNull(cache)){
                if (cache.getCount() > 0){
                    cache.setCount(cache.getCount() > 0 ? cache.getCount()-1 : 0);
                    SpringUtils.getBean(RedisCache.class).setCacheObject(getCacheKey(key),cache,15,TimeUnit.MINUTES);
                }
            }
        }
    }

    public static void removeConnect(Integer key){
        SpringUtils.getBean(RedisCache.class).deleteObject(getCacheKey(key));
    }

    public static boolean keepLive(Integer key){
        synchronized (MediaVideoUtils.class){
            CameraCache cache  = SpringUtils.getBean(RedisCache.class).getCacheObject(getCacheKey(key));
            if (StringUtils.isNull(cache)){
                log.info("摄像头：{} ，视频流保活失败",key);
                return false;
            }
            SpringUtils.getBean(RedisCache.class).setCacheObject(getCacheKey(key),cache,15,TimeUnit.MINUTES);
            log.info("摄像头：{} ，视频流保活成功",key);
            return true;
        }
    }

    public static boolean exists(Integer key){
        CameraCache cache = SpringUtils.getBean(RedisCache.class).getCacheObject(getCacheKey(key));
        if (StringUtils.isNull(cache)) {
            return false;
        }

        if (cache.getCount() > 0){
            return true;
        }

        return false;
    }

    /**
     * 设置cache key
     *
     * @param key 参数键
     * @return 缓存键key
     */
    private static String getCacheKey(Integer key)
    {
        return CacheConstants.CAMERA_KEY + key;
    }
}
